package com.wcbdota.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

@SuppressLint("HandlerLeak")
public class AsyncImageLoader {
	private View view;
	private HashMap<String, SoftReference<Bitmap>> imageCache;

	public AsyncImageLoader() {
		this.imageCache = new HashMap<String, SoftReference<Bitmap>>();
		this.view = null;
	}
	
	public AsyncImageLoader(View view) {
		this.view = view;
		this.imageCache = new HashMap<String, SoftReference<Bitmap>>();
	}
	
	public void setview(View view){
		this.view = view;
	}

	public Bitmap loadBitmap(final String imageUrl,
			final ImageCallback imageCallback) {
		
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
			Bitmap bitmap = softReference.get();
			if (bitmap != null) {
				return bitmap;
			}
		}

		final Handler imageLoadSuccesshandler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoadSuccess((Bitmap) message.obj, imageUrl, view);
			}
		};
		
		final Handler imageLoadedErrorhandler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoadError(imageUrl, view);
			}
		};
		
		new Thread() {
			@Override
			public void run() {
				Bitmap bitmap = loadImageFromUrl(imageUrl);
				if(bitmap != null){
					imageCache.put(imageUrl, new SoftReference<Bitmap>(bitmap));
					Message message = imageLoadSuccesshandler.obtainMessage(0, bitmap);
					imageLoadSuccesshandler.sendMessage(message);
				} else{
					Message message = imageLoadedErrorhandler.obtainMessage(0);
					imageLoadedErrorhandler.sendMessage(message);
				}

			}
		}.start();
		return null;
	}

	public static Bitmap loadImageFromUrl(String urlstring) {
		URL url = null; 
		Bitmap bitmap = null;  
		Log.w("img url", urlstring);
		try {
			url = new URL(urlstring);  
			
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();  

			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();  
			bitmap = BitmapFactory.decodeStream(is);  

			is.close();  

		} catch (IOException e) {  
		  e.printStackTrace();  
		}  
		return bitmap;
	}

	public interface ImageCallback {
//		public void imageLoadSuccess(Bitmap imageBitmap, String imageUrl);
//		public void imageLoadError(String imageUrl);
		
		public void imageLoadSuccess(Bitmap imageBitmap, String imageUrl, View view);
		public void imageLoadError(String imageUrl, View view);
	}
}